package com.wpp;

import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

public class Conntest {

    //创建获取数据库的连接方法
    public Connection getConnection() throws Exception{
        //加载配置文件
        InputStream resourceAsStream = Conntest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //创建properties对象
        Properties properties = new Properties();
        //把数据流加载到properties中
        properties.load(resourceAsStream);

        //读取数据
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        //加载驱动
        Class.forName(driver);

        //获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        //预编译sql
        String sql = "select * from test where id={?}";

        //
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //设置参数
        preparedStatement.setObject(0,"2");
        //执行sql
        preparedStatement.execute();

        //返回连接

        return connection;
    }

    /**
    *用于测试:
    *
    */
    @Test
    public void test(){
        Conntest conntest = new Conntest();
        try {
            Connection connection = conntest.getConnection();
            System.out.println(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
